import { Component, Injector, ViewChild, ViewEncapsulation, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AppConsts } from '@shared/AppConsts';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { HttpClient } from '@angular/common/http';
import { DeliveryServiceProxy, ProcessingOrderServiceProxy, TaskServiceProxy, OutsourcingServiceProxy } from '@shared/service-proxies/service-proxies';
import { FileDownloadService } from '@shared/utils/file-download.service';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { CreateOrEditTaskModalComponent } from './create-or-edit-task-modal/create-or-edit-task-modal.component';
import { finalize } from 'rxjs/operators';
import { TaskService } from './Task.service';
import * as _ from 'lodash';
import { from } from 'rxjs';
import { SelectItem } from 'primeng/api';


@Component({
    selector: 'app-task',
    templateUrl: './task.component.html',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./task.component.css'],
    animations: [appModuleAnimation()]
})
export class TaskComponent extends AppComponentBase implements OnInit {

    @ViewChild('createOrEditTaskModal') createOrEditTaskModal: CreateOrEditTaskModalComponent;
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;

    filterText = '1';
    selectedPermission = '';
    role = '';
    code = 'code';
    taskType = 0;
    isReceived = true;
    isCompleted = false;
    onlyLockedUsers = false;
    advancedFiltersAreShown = false;
    taskTypeAyy = [];

    ngOnInit() {
        this.taskTypeAyy = [
            { label: '主制任务', value: 0 },
            { label: '辅制任务', value: 1 }
        ];
    }

    constructor(
        injector: Injector,
        private _taskServiceProxy: TaskServiceProxy,
        private _deliveryServiceProxy: DeliveryServiceProxy,
        private _processingOrderServiceProxy: ProcessingOrderServiceProxy,
        private _outsouringServiceProxy: OutsourcingServiceProxy,
        private _fileDownloadService: FileDownloadService,
        private _activatedRoute: ActivatedRoute,
        private _httpClient: HttpClient,
        private _taskService: TaskService
    ) {
        super(injector);
        this.filterText = this._activatedRoute.snapshot.queryParams['filterText'] || '';
    }



    exportToExcel(): void {
        // this._taskServiceProxy.getTaskForModel(
        //     this.filterText,
        //     this.primengTableHelper.getSorting(this.dataTable),
        //     this.primengTableHelper.getMaxResultCount(this.paginator, event),
        //     this.primengTableHelper.getSkipCount(this.paginator, event),
        //     )
        //     .subscribe(result => {
        //         this._fileDownloadService.downloadTempFile(result);
        //     });
    }

    onUploadExcelError(): void {
        this.notify.error(this.l('ImportUsersUploadFailed'));
    }

    createTask(): void {
        this.createOrEditTaskModal.show();
    }

    getTasks(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);

            return;
        }
        this.primengTableHelper.showLoadingIndicator();

        console.log(this.taskType);
        this._taskServiceProxy.getTaskForModel(
            this.taskType,
            this.filterText,
            //this.isReceived,
            undefined,
            undefined,
            this.isCompleted,
            0,
            this.primengTableHelper.getSkipCount(this.paginator, event),
            this.primengTableHelper.getMaxResultCount(this.paginator, event)
        ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            console.log(result);
            this.primengTableHelper.hideLoadingIndicator();

            _.forEach(result.items, viewItem => {
                console.log(viewItem);
                let currentD = result.items.find((element) => (element.id === viewItem.id));
                if (!!viewItem.id) {
                    this._deliveryServiceProxy.getDeliveryAmountWorkFlowComplete(viewItem.id, '')
                        .subscribe(result => {
                            currentD.deliveryNum = result;
                        });
                    this._processingOrderServiceProxy.getProcessingAmountForTaskId(viewItem.id, '').subscribe(result => {
                        currentD.processingNum = result;
                    });

                    this._outsouringServiceProxy.getOutsourcingApplyCount(viewItem.id).subscribe(result => {
                        currentD.outsourcingNum = result;
                    });

                } else {
                    currentD.deliveryNum = 0;
                    currentD.processingNum = 0;
                    currentD.outsourcingNum = 0;
                }




            });
        });
    }
}
